<template>
  <div class="main" >
    <el-row gutter="20">

      <!--左侧导航栏 -->
      <el-col span="3">
        <el-menu :default-active="activeIndex"
                 class="el-menu-vertical-demo"
                 text-color="rgb(39,137,150)">
          <el-menu-item index="1">
            <a href="javascript:void(0)" @click="goToInvoice" style="color: rgb(39,137,150)"><span slot="title">我的发票</span></a>
          </el-menu-item>
          <el-menu-item index="2">
            <span slot="title">我的订单</span>
          </el-menu-item>
        </el-menu>
      </el-col>

      <!--订单主页 -->
      <el-col span="21">
        <!--头部菜单 -->
        <el-menu :default-active="activeIndex2" class="el-menu-demo" mode="horizontal" @select="handleSelect">
          <el-menu-item index="1">全部订单</el-menu-item>
          <el-menu-item index="2">待付款</el-menu-item>
          <el-menu-item index="3">未出行</el-menu-item>
          <el-menu-item index="4">已退款</el-menu-item>
        </el-menu>

        <!--订单列表 -->
        <el-card>
          <!-- 订单搜索-->
          <el-input placeholder="请输入订单信息"  class="input-with-select" v-model="keyword" @keydown.native.enter="searchOrder()">
            <el-select v-model="selectOrder"  slot="prepend" placeholder="请选择">
              <el-option label="全部" value=0></el-option>
              <el-option v-for="t in typeArr" :label="t.name" :value="t.id"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="searchOrder()"></el-button>
          </el-input>

          <!-- 订单信息-->
          <el-card class="order_card" v-for="c in contentArr">

            <div class="order_title">
              <span>
                订单号：<a href="javascript:void(0)" @click="orderDetail(c)">{{ c.orderNo }}</a>
                <el-dialog class="detail" title="订单详情" :visible.sync="dialogVisibleOrder" width="750px">
                  <div class="detail_top">
                    <h4 style="font-size: 20px;color: #aaaaaa" v-if="gridData.status==='REFUD_SUCCESS'">已退款</h4>
                    <h4 style="font-size: 20px;color: #aaaaaa" v-if="gridData.status==='CANCEL_SUCCESS'">已取消</h4>
                    <h4 style="font-size: 20px;color: dodgerblue" v-if="gridData.status==='WAIT_BUYER_PAY'">待付款</h4>
                    <h4 style="font-size: 20px;color: dodgerblue" v-if="gridData.status==='TRADE_SUCCESS' && gridData.useStatus===0">待使用</h4>
                    <h4 style="font-size: 20px;color: dodgerblue" v-if="gridData.status==='TRADE_SUCCESS' && gridData.useStatus===1">已完成</h4>
                  </div>

                  <el-descriptions :column="1" border label-class-name="description-label">
                    <el-descriptions-item label="订单号">{{gridData.orderNo}}</el-descriptions-item>
                    <el-descriptions-item label="姓名">{{gridData.useName}}</el-descriptions-item>
                    <el-descriptions-item label="产品">{{gridData.subject}}</el-descriptions-item>
                    <el-descriptions-item label="类型">{{gridData.name}}</el-descriptions-item>
                    <el-descriptions-item label="数量">{{gridData.quantity}}</el-descriptions-item>
                    <el-descriptions-item label="总价">{{gridData.totalAmount}}</el-descriptions-item>
                    <el-descriptions-item label="下单时间">{{gridData.createTime}}</el-descriptions-item>
                    <el-descriptions-item v-if="gridData.startTime!=gridData.endTime" label="预约时间">{{gridData.startTime}}~{{gridData.endTime}}</el-descriptions-item>
                    <el-descriptions-item v-else>{{gridData.startTime}}</el-descriptions-item>
                    <el-descriptions-item label="邮箱">{{gridData.email}}</el-descriptions-item>
                    <el-descriptions-item label="电话号码">{{gridData.phone}}</el-descriptions-item>
                  </el-descriptions>
                </el-dialog>
              </span>
              <span>预定日期：{{c.createTime}}</span>
              <span><a v-if="c.status!=='WAIT_BUYER_PAY' && !(c.status==='TRADE_SUCCESS' && c.useStatus===0)"
                       href="javascript:(0)" @click="deleteOrder(c)">删除订单</a></span>
            </div>
            <div class="order_body" style="overflow: hidden">
              <div class="body_left" >
                <h4 style="font-size: 20px">{{c.subject}}</h4>
                <p v-if="c.startTime!=c.endTime">预约日期：{{c.startTime}}至{{c.endTime}}</p>
                <p v-else>预约日期：{{c.startTime}}</p>
                <p>姓名：{{c.useName}}</p>
                <p>类型：{{c.name}}</p>
              </div>
              <div class="body_right">
                <h4 style="font-size: 15px;color: #aaaaaa" v-if="c.status==='REFUD_SUCCESS'">已退款</h4>
                <h4 style="font-size: 15px;color: #aaaaaa" v-if="c.status==='CANCEL_SUCCESS'">已取消</h4>
                <h4 style="font-size: 15px;color: dodgerblue" v-if="c.status==='WAIT_BUYER_PAY'">待付款</h4>
                <h4 style="font-size: 15px;color: dodgerblue" v-if="c.status==='TRADE_SUCCESS' && c.useStatus===0">待使用</h4>
                <h4 style="font-size: 15px;color: dodgerblue" v-if="c.useStatus===1">已完成</h4>
                总价<span style="font-weight: bold;font-size: 20px">￥{{c.totalAmount}}</span>
              </div>
            </div>
            <div class="order_footer" style="overflow: hidden;">
              <div style="float: right" v-if="c.status=='WAIT_BUYER_PAY'">
                <el-button  @click="pay(c)"><span>付款</span></el-button>
                <el-button  @click="cancel(c)"><span>取消订单</span></el-button>
              </div>
              <div style="float: right" v-if="c.status=='TRADE_SUCCESS' && c.useStatus===0">
                <el-button  @click="refund(c)"><span>退款</span></el-button>
              </div>
              <div style="float: right" v-if="c.status=='TRADE_SUCCESS' && c.useStatus===1">
                <el-button  @click="openInvoice(c)"><span>申请发票</span></el-button>
                <el-dialog class="open" title="开票信息" :visible.sync="dialogVisibleInvoice" width="750px">
                  <el-form :model="openData" :rules="rules">
                    <el-form-item label="发票类型" :label-width="formLabelWidth">
                      <el-input value="电子发票"></el-input>
                    </el-form-item>
                    <el-form-item label="产品内容" :label-width="formLabelWidth">
                      <el-input :value="openData.subject"></el-input>
                    </el-form-item>
                    <el-form-item label="发票金额" :label-width="formLabelWidth">
                      <el-input :value="openData.totalAmount"></el-input>
                    </el-form-item>
                    <el-form-item label="开票方式" :label-width="formLabelWidth">
                      <el-radio v-model="openData.content" label="商品类别"></el-radio>
                      <el-radio v-model="openData.content" label="商品明细"></el-radio>
                    </el-form-item>
                    <el-form-item prop="title" label="发票抬头" :label-width="formLabelWidth">
                      <el-input v-model="openData.title" ></el-input>
                    </el-form-item>
                    <el-form-item prop="taxNumber" label="纳税人识别号" :label-width="formLabelWidth">
                      <el-input v-model="openData.taxNumber"></el-input>
                    </el-form-item>
                    <el-form-item prop="phone" label="电话号码" :label-width="formLabelWidth">
                      <el-input v-model="openData.phone" ></el-input>
                    </el-form-item>
                    <el-form-item prop="address" label="地 址" :label-width="formLabelWidth">
                      <el-input v-model="openData.address" ></el-input>
                    </el-form-item>
                  </el-form>
                  <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogVisibleInvoice = false">取 消</el-button>
                    <el-button type="primary" @click="applyInvoice('openData')"><span style="color: white">提交申请</span></el-button>
                  </div>
                </el-dialog>
              </div>
              <div style="float: right" v-if="c.status=='APPLYING'">
                <el-button  @click="viewInvoice(c)"><span>查看发票</span></el-button>
                <el-dialog class="open" title="开票信息" :visible.sync="dialogVisibleViewInvoice" width="750px">
                  <div class="viewInvoice">
                    <h4 style="font-size: 30px;color: dodgerblue" v-if="viewOpenData.status==='APPLYING'">申请中</h4>
                    <h4 style="font-size: 30px;color: dodgerblue" v-if="viewOpenData.status==='APPROVED'">申请通过</h4>
                    <h4 style="font-size: 30px;color: dodgerblue" v-if="viewOpenData.status==='FAILED'">申请未通过</h4>
                  </div>
                  <el-descriptions :column="1" border label-class-name="description-label">
                    <el-descriptions-item label="发票类型">电子发票</el-descriptions-item>
                    <el-descriptions-item label="产品内容">{{viewOpenData.subject}}</el-descriptions-item>
                    <el-descriptions-item label="发票金额">{{viewOpenData.totalAmount}}</el-descriptions-item>
                    <el-descriptions-item label="开票方式">{{viewOpenData.content}}</el-descriptions-item>
                    <el-descriptions-item label="发票抬头">{{viewOpenData.title}}</el-descriptions-item>
                    <el-descriptions-item label="纳税人识别号">{{viewOpenData.taxNumber}}</el-descriptions-item>
                    <el-descriptions-item label="电话号码">{{viewOpenData.phone}}</el-descriptions-item>
                    <el-descriptions-item label="地 址">{{viewOpenData.address}}</el-descriptions-item>
                  </el-descriptions>

                </el-dialog>
              </div>
            </div>
          </el-card>
          <download-excel v-if="contentArr.length>0" style="margin-top: 10px" class="downloadExcel" :data="exportArr" types="xls" :fields="fields" name="订单" worksheet="订单">
            <el-button type="primary" @click="exportOrder"><span style="color: white">导出</span></el-button>
          </download-excel>
          <el-card v-if="contentArr.length==0" style="height: 200px;text-align: center;background-color: #cccccc">
            <p style="color: black;line-height: 180px">暂无相关订单</p>
          </el-card>

        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
export default{
    data: function () {
      return {
        activeIndex:'2',
        activeIndex2:'1',
        //选择搜索类型的下标
        selectOrder: '0',
        contentArr:[],
        exportArr:[],
        keyword:'',
        typeArr:[{id:1,name:'酒店'},{id:2,name:'旅游'},{id:3,name:'门票'}],
        dialogVisibleOrder: false,
        dialogVisibleInvoice: false,
        dialogVisibleViewInvoice: false,
        gridData:'',
        payInfo:{},
        contentStatus:'all',
        openData:{orderId:'',subject:'',totalAmount:'',phone:'',content:'商品类别',title:'',taxNumber:'',address:''},
        viewOpenData:{orderId:'',subject:'',totalAmount:'',phone:'',content:'',title:'',taxNumber:'',address:'',status:''},
        formLabelWidth: '150px',
        fields: {编号: 'id', 订单号: 'orderNo', 产品: 'subject', 类型: 'name', 数量: 'quantity', 总价: 'totalAmount', 使用者: 'useName', 邮箱: 'email',
          电话: 'phone', 状态: 'status', 创建时间: 'createTime', 开始时间: 'startTime', 结束时间: 'endTime',},
        rules: {
          phone:[{ required: true, message: '请填写手机号码', trigger: 'blur' },
            { min: 11, max: 11, message: '手机号码不低于11位数', trigger: 'blur' },
            { pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/, message: '请输入正确的手机号码格式' }],
          taxNumber:[{ required: true, message: '请填写纳税人识别号', trigger: 'blur' }],
          address:[{ required: true, message: '请填写地址', trigger: 'blur' }],
          title:[{ required: true, message: '请填写发票抬头', trigger: 'blur' }]
        }
      }
    },

    methods: {
      //填入导出信息
      exportOrder(){
        this.exportArr=this.contentArr;
        for (let i = 0; i < this.exportArr.length; i++) {
          if(this.exportArr[i].status==='REFUD_SUCCESS'){
            this.exportArr[i].status='已退款';
          }
          if(this.exportArr[i].status==='CANCEL_SUCCESS'){
            this.exportArr[i].status='已取消';
          }
          if(this.exportArr[i].status==='WAIT_BUYER_PAY'){
            this.exportArr[i].status='待付款';
          }
          if(this.exportArr[i].status==='TRADE_SUCCESS' && this.exportArr[i].useStatus===0){
            this.exportArr[i].status='待使用';
          }
          if(this.exportArr[i].useStatus===1){
            this.exportArr[i].status='已完成';
          }
        }
      },
      //查看发票
      viewInvoice(order){
        this.axios
            .create({"headers":{"Authorization":localStorage.getItem("localJwt")}})
            .get("http://localhost:8080/v1/invoices/"+order.id+"/view").then((response)=>{
          if(response.data.code==1){
            this.viewOpenData=response.data.data;
            this.viewOpenData.totalAmount=order.totalAmount;
            this.dialogVisibleViewInvoice=true;
          }
        })
      },
      //提交开票信息
      applyInvoice(info){
          this.axios
              .create({"headers": {"Authorization": localStorage.getItem("localJwt")}})
              .post("http://localhost:8080/v1/invoices/insert", this.openData).then((response) => {
            if (response.data.code == 1) {
              this.$message({
                message: '提交成功！',
                type: 'success'
              });
              this.dialogVisibleInvoice = false;
              this.loadContent(this.contentStatus);
            }
          })
      },
      //付款
      pay(order){
        console.log("+++"+order)
        this.payInfo=order;
        this.payInfo.startTime=new Date(order.startTime);
        this.payInfo.endTime=new Date(order.endTime);

        this.axios
            .create({"headers":{"Authorization":localStorage.getItem("localJwt")}})
            .post("http://localhost:8080/alipay/trade/",order).then((response)=>{
              console.log(response.data)
            const div=document.createElement('div')
            div.innerHTML = response.data;
            document.body.appendChild(div);
            document.forms['punchout_form'].setAttribute('target','_blank');
            document.forms['punchout_form'].submit()
            order.startTime=this.formatDate(order.startTime)
            order.endTime=this.formatDate(order.endTime)
            this.$confirm('您是否已经付款?', '提示', {
              confirmButtonText: '我已付款',
              cancelButtonText: '取消',
            }).then(async () => {
              this.axios
                  .create({"headers":{"Authorization":localStorage.getItem("localJwt")}})
                  .post("http://localhost:8080/alipay/"+order.orderNo+"/status").then((response)=>{
                if(response.data.code==1){
                  this.loadContent(this.contentStatus);
                }else {
                  this.$message({
                    message: response.data.msg,
                    type: 'warning'
                  });
                  this.loadContent(this.contentStatus);
                }
              })
            }).catch((e) => {
              this.loadContent(this.contentStatus);
            })

        })
      },

      //取消订单
      cancel(order){
        this.$confirm('您确定要取消此订单吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          this.axios
              .create({"headers":{"Authorization":localStorage.getItem("localJwt")}})
              .post("http://localhost:8080/v1/orders/"+order.id+"/cancel").then((response)=>{
            if(response.data.code==1){
              this.$message({
                message: '取消订单成功！',
                type: 'success'
              });
              this.loadContent(this.contentStatus);
            }
          })
        }).catch((e) => {
          console.log(e)
          this.$message.info('已取消')
        })
      },
      //订单退款
      refund(order){
        this.$confirm('您确定要退款吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          this.axios
              .create({"headers":{"Authorization":localStorage.getItem("localJwt")}})
              .post("http://localhost:8080/v1/orders/"+order.id+"/refund").then((response)=>{
            if(response.data.code==1){
              this.$message({
                message: '订单退款成功！',
                type: 'success'
              });
              this.loadContent(this.contentStatus);
            }
          })
        }).catch((e) => {
          console.log(e)
          this.$message.info('已取消退款')
        })
      },
      //开票信息
      openInvoice(order){
        this.dialogVisibleInvoice=true;
        this.openData.orderId=order.id;
        this.openData.totalAmount=order.totalAmount;
        this.openData.phone=order.phone;
        this.openData.subject=order.subject;
      },
      //订单详情
      orderDetail(order){
        console.log(order);
        this.dialogVisibleOrder=true;
        this.gridData=order;
      },

      //删除订单
      deleteOrder (order) {
          this.$confirm('您确定要删除此订单吗?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
          }).then(async () => {
            this.axios
                .create({"headers":{"Authorization":localStorage.getItem("localJwt")}})
                .post("http://localhost:8080/v1/orders/"+order.id+"/delete").then((response)=>{
              if(response.data.code==1){
                this.$message({
                  message: '订单删除成功！',
                  type: 'success'
                });
                this.loadContent(this.contentStatus);
              }
            })
          }).catch((e) => {
              console.log(e)
              this.$message.info('已取消删除')
          })
      },
      //搜索订单
      searchOrder(){
        this.axios
            .create({"headers":{"Authorization":localStorage.getItem("localJwt")}})
            .get("http://localhost:8080/v1/orders/"+this.selectOrder+"/search?keyword="+this.keyword).then((response)=>{
            if(response.data.code==1){
              this.contentArr=response.data.data;
              console.log(this.contentArr)
            }
        })
      },
      //选择订单状态
      handleSelect(key, keyPath) {
        if(key==1){
          this.contentStatus="all"
        }
        if(key==2){
          this.contentStatus="WAIT_BUYER_PAY"
        }
        if(key==3){
          this.contentStatus="TRADE_SUCCESS"
        }
        if(key==4){
          this.contentStatus="REFUD_SUCCESS"
        }
        console.log(this.contentStatus)
        this.loadContent(this.contentStatus);
      },
      //根据订单状态显示订单列表
      loadContent(status){
        this.axios
            .create({"headers":{"Authorization":localStorage.getItem("localJwt")}})
            .get("http://localhost:8080/v1/orders/"+ status +"/orderList").then((response)=>{
          if(response.data.code==1){
            this.contentArr=response.data.data;
            console.log(this.contentArr)
          }
        })
      },

      goToInvoice() {
        if (location.href == 'http://localhost:9090/invoice') {
          location.reload();
          return;
        }
        this.$router.push('/invoice');
      },
      formatDate (d) {
        var date = new Date(d);
        var YY = date.getFullYear() + '-';
        var MM =
            (date.getMonth() + 1 < 10
                ? '0' + (date.getMonth() + 1)
                : date.getMonth() + 1) + '-';
        var DD = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
        return YY + MM + DD;
      },
    },

    mounted(){
      this.loadContent('all');
    },
    created() {
      if(!localStorage.getItem("id")) {
        this.$message.error("请先登录")
        setTimeout(() => {
          history.back()
        }, 1000)
      }
    }
}
</script>

<style scoped>


.main{
  margin: 0 auto;
  width: 1200px;
}
.main a{
  color: dodgerblue;
}
.order_card{
  margin-top: 10px;
  padding: 0;
  border: 1px solid #d9d9d9;
  border-radius: 0;
}
/deep/.el-card__body {
  padding: 0;
}
.order_card:hover{
  border: 1px solid dodgerblue;
}
.order_title{
  height: 34px;
  background-color: #F6F6F6;
}
.order_title span{
  line-height: 34px;
  font-size: 14px;
  margin-left: 20px;
}
.order_title a:hover{
  text-decoration: underline ;
}
.order_body p,h4{
  margin: 5px 0 0 0;
  padding: 0;
  font-size: 14px;
}
.order_body{
  margin-bottom: 15px;
}

.body_left{
  float: left;
  margin-left: 30px;
}
.body_right{
  float: right;
  margin-right: 20px;
}

.order_footer button{
  width: 100px;
  border-radius: 3px;
  border: dodgerblue solid 1px;
  margin:0 15px 15px 0;
}
.order_footer span{
  color:dodgerblue;
}

.detail .el-input{
  width: 300px;
}
.detail_div{
  margin: 20px 0 0 20px;
}
.detail_div span{
  display: inline-block;
  width:70px;
}

/deep/.el-dialog__body{
  padding-top: 0;
}

.detail_top{
  margin-left: 40px;
  margin-bottom: 40px;
}
.detail_top h4{
  display: inline-block;
}
el-button el-button--primary span{
  color: white;
}

.viewInvoice{
  margin-left: 20px;
  margin-bottom: 20px;
}

</style>